
package com.test.auth.code.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.tomcat.util.json.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @description: Jwt工具类，生成JWT和认证
 * @author: ccl
*/

public class JwtUtil {

    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

/**
     * 密钥
     */

    private static final String SECRET = "my_secret";


/**
     * 过期时间
     **/

    private static final long EXPIRATION = 1800L;//单位为秒


/**
     * 生成用户token,设置token超时时间
     */

    /*public static String createToken(UserInfo user) {
        //过期时间
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                .withHeader(map)// 添加头部
                //可以将基本信息放到claims中
                .withClaim("loginId", user.getLoginId())//登录账号
                .withClaim("deptCode", user.getDeptCode())//部门编码
                .withClaim("parentCode", user.getDeptCode())//父编码
                .withClaim("roleCode", user.getRoleCode())//角色编码
                .withExpiresAt(expireDate) //超时设置,设置过期的日期
                .withIssuedAt(new Date()) //签发时间
                .sign(Algorithm.HMAC256(SECRET)); //SECRET加密
        return token;
    }*/

/**
     * 校验token并解析token
     */

    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);

            //decodedJWT.getClaim("属性").asString()  获取负载中的属性值

        } catch (Exception e) {
            logger.error(e.getMessage());
            logger.error("token解码异常");
            //解码异常则抛出异常
            return null;
        }
        return jwt.getClaims();
    }

    /**
     * loginId
     * test2
     * ----------
     * orgPath
     * D01001
     * ----------
     * userName
     * 测试人员2
     * ----------
     * exp
     * null
     * ----------
     * iat
     * null
     * ----------
     * userCode
     * 000001
     * ----------
     * deptCode
     * D01001
     * @param args
     */
    public static void main(String[] args) {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbklkIjoiYWRtaW4iLCJvcmdQYXRoIjoiRCIsInVzZXJOYW1lIjoi6LaF57qn566h55CG5ZGYIiwiZXhwIjoxNjgzNTMzMjUyLCJpYXQiOjE2ODMyNzQwNTIsInVzZXJDb2RlIjoiMDAwMDAwIiwiZGVwdENvZGUiOiJEIn0.Ms-RXxbksSIZNqQcgwNv0AHQzmsQ8gEfHR8lNNV3eQs";

        Map<String, Claim> stringClaimMap = verifyToken(token);
        //Claim keyValue = stringClaimMap.get("parentCode");
        //System.out.println(keyValue == null);
        for (String key : stringClaimMap.keySet()){
            System.out.println(key);
            System.out.println(stringClaimMap.get(key).asString());
            System.out.println("----------");
        }
    }
}
